package controllers

import (
	"IrisService/models"

	"github.com/jinzhu/gorm"
	"github.com/kataras/iris/v12"
)

type EntryController struct {
	*baseController
}

func NewEntryController(db *gorm.DB) *EntryController {
	props := []string{
		"_apis",
		"entry/#entry",
		"POST:"}
	item := &baseController{
		entry: "Entry",
		db:    db,
		model: models.EntryItem{},
		props: props}
	return &EntryController{item}
}

func (c *EntryController) GetEntryBy(entry string) iris.Map {
	if len(entry) == 0 {
		return c.Fail()
	} else {
		items := new([]models.EntryItem)
		c.db.Where("entry LIKE ?", "%"+entry+"%").Find(items)
		return c.GenDetails(items)
	}
}

func (c *EntryController) GetUidBy(entry string) iris.Map {
	if len(entry) == 0 {
		return c.Fail()
	} else {
		item := new(models.EntryItem)
		c.db.Where("entry=?", entry).First(item)
		return c.Rise(item.Detail)
	}
}

func (c *EntryController) Post(ctx iris.Context) iris.Map {
	item := new(models.EntryItem)
	if err := ctx.ReadJSON(item); err != nil {
		return c.Fail()
	} else {
		return c.Rise(c.db.Create(item).RowsAffected)
	}
}
